<template>
  <div class="app-container">
    <el-dialog
      :title="title"
      :visible.sync="open2"
      v-if="open2 == true"
      width="960px"
      append-to-body
      @close="cancelMerger"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单编号" prop="workorderCode">
              <el-input v-model="form.workorderCode" placeholder="" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单名称" prop="workorderName">
              <el-input v-model="form.workorderName" placeholder="" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品编号" prop="productCode">
              <el-input v-model="form.productCode" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="BOM编号" prop="bomCode">
              <el-input v-model="form.bomCode" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="BOM版本" prop="bomName">
              <el-input v-model="form.bomName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划开工日期" prop="startDate">
              <el-date-picker
                clearable
                v-model="form.startDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择计划开工日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划完工日期" prop="endDate">
              <el-date-picker
                clearable
                v-model="form.endDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择计划完工日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单数量" prop="quantity">
              <el-input-number :min="0" v-model="form.quantity" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="需求日期" prop="requestDate">
              <el-date-picker
                clearable
                v-model="form.requestDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择需求日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider content-position="center">合并明细</el-divider>
      <el-card shadow="always" class="box-card">
        <el-table border v-loading="loading" :data="workorderList">
          <el-table-column label="工单编码" width="150" prop="workorderCode">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="handleView(scope.row)" v-hasPermi="['mes:pro:workorder:query']"
                >{{ scope.row.workorderCode }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column
            label="工单名称"
            width="150"
            align="center"
            prop="workorderName"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="图号" width="200" align="center" prop="attr2" :show-overflow-tooltip="true" />
          <el-table-column label="关联计划" width="200" align="center" prop="planName" :show-overflow-tooltip="true" />
          <el-table-column label="计划编号" width="150" align="center" prop="planCode" :show-overflow-tooltip="true" />
          <el-table-column
            label="产品编号"
            width="120"
            align="center"
            prop="productCode"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="产品名称"
            width="100"
            align="center"
            prop="productName"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="规格型号"
            width="150"
            align="center"
            prop="productSpc"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="单位" width="60" align="center" prop="unitOfMeasure" />
          <el-table-column label="需求日期" align="center" prop="requestDate" width="120">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.requestDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="计划开工时间" align="center" width="120px" prop="startDate">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="计划完工时间" align="center" width="120px" prop="endDate">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="工单数量" width="80" align="center" prop="quantity">
            <template slot-scope="scope">
              <el-tag type="danger">{{ scope.row.quantity }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="80px">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-card>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMerger">保 存</el-button>
        <el-button @click="cancelMerger">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mergerList, addMergerList, mergerWorkorder } from '@/api/mes/pro/workticket';
import { genCode } from '@/api/system/autocode/rule';

export default {
  name: 'SchedulingLine',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料需求
      workorderList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open2: false,
      form: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        workorderIds: null,
        productId: null,
        productCode: null,
        productName: null
      },
      rules: {
        workorderCode: [{ required: true, message: '工单编码不能为空', trigger: 'blur' }],
        workorderName: [{ required: true, message: '工单名称不能为空', trigger: 'blur' }],
        startDate: [{ required: true, message: '计划开工日期不能为空', trigger: 'blur' }],
        endDate: [{ required: true, message: '计划完工日期不能为空', trigger: 'blur' }],
        requestDate: [{required: true, message: '需求日期不能为空', trigger: 'blur'}],
      }
    };
  },
  methods: {
    init(id) {
      mergerWorkorder(id).then(response => {
        this.form = response.data;
        this.open2 = true;
        this.title = '合并工单';
        this.optType = 'add';
      });
      this.queryParams.workorderIds = id;
      this.getList();
    },
    /** 查询生产工单BOM组成列表 */
    getList() {
      this.loading = true;
      this.workorderList = [];
      mergerList(this.queryParams).then(response => {
        this.workorderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleDelete(row) {
      this.$confirm('确定要取消此工单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const index = this.workorderList.findIndex(item => item.id === row.id);
          if (index !== -1) {
            // 删除工单
            this.workorderList.splice(index, 1);
            // 更新 workorderIds（只保留未删除的）
            this.form.workorderIds = this.workorderList.map(item => item.id);
            // 重新计算合并后的总 quantity（注意转换为数字）
            this.form.quantity = this.workorderList.reduce((sum, item) => {
              return sum + Number(item.quantity || 0);
            }, 0);
          }
          this.$message.success('取消成功');
        })
        .catch(() => {});
    },

    submitMerger() {
      if (!this.workorderList || this.workorderList.length < 2) {
        this.$modal.msgWarning('请至少选择两个工单进行合并操作!');
        return;
      }
      this.$modal
        .confirm('是否合并工单？合并后只生成一条生产工单')
        .then(() => {
          this.$refs['form'].validate(valid => {
            if (valid) {
              addMergerList(this.form).then(response => {
                if (response.code === 200) {
                  this.$emit('cancelMerger');
                  this.$emit('refreshList');
                  this.open2 = false;
                  this.$modal.msgSuccess('执行成功');
                }
              });
            }
          });
        })
        .catch(() => {});
    },
    // 取消按钮
    cancelMerger() {
      this.$emit('cancelMerger');
      this.open2 = false;
    }
  }
};
</script>
